dojo.provide("xray.tools.Screenshot");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.requireLocalization("xray.tools", "Screenshot");

dojo.declare(
	"xray.tools.Screenshot", 
	[dijit._Widget, dijit._Templated], 
	{
	
	templateString: '<span dojoAttachEvent="onclick: takeScreenshot" class="iconScreenshot"><img src="${iconScreenshot}" /></span>',
	iconScreenshot: dojo.moduleUrl("xray.tools.resources", "iconScreenshot.png"),
	
	postCreate: function(){
		dojo.mixin(this, dojo.i18n.getLocalization("xray.tools", "Screenshot", this.lang));
	},
	
	takeScreenshot: function(){
		this.docsDir = air.File.desktopDirectory.resolvePath(dojo.date.locale.format(new Date(), {datePattern: "yyyy-MM-dd", timePattern: "HH-mm"})+" xRay screenshot.png");
		this.docsDir.browseForSave(this.saveFile);
		this.docsDir.addEventListener(air.Event.SELECT, dojo.hitch(this, "_writeData"));
		
		// write image data
		var rect = dojo.coords(dojo.byId("mainGraphContent"));
		
		var bmp = new air.BitmapData( rect.w - 2, rect.h - 2 );
		var matrix = new air.Matrix();

		matrix.translate( 0 - ( rect.x + 1 ), 0 - ( rect.y + 1 ) ); 
		bmp.draw( window.htmlLoader, matrix );
		
		this.png = runtime.com.adobe.images.PNGEncoder.encode( bmp );
	},
	
	_writeData: function(e){
		// file dialog to create file name
		this.docsDir.removeEventListener(air.Event.SELECT, dojo.hitch(this, "_writeData"));
		
		var tmpArr = air.File(e.target).nativePath.split(air.File.separator);
		var fileName = tmpArr.pop();//remove last array item and return its content
		
		// in the case we don't provide an extension or wrong type we change file to correct extension
		var saveFilename = this._checkExtension(fileName);
		tmpArr.push(saveFilename);
		
		// create new file object
		var file = new air.File(tmpArr.join(air.File.separator));
		
		// save to stream
		var stream = new air.FileStream();
		stream.open( file, air.FileMode.WRITE );
		stream.writeBytes( this.png, 0, 0 );
		stream.close();
	},
	
	_checkExtension: function(file){
		var extension = file.split(".")[1];
		if (extension == "png"){
			return file;
		}
		return file.split(".")[0] + ".png";
	}
});